package com.clf.manager.controller;

import com.clf.manager.entity.User;
import com.clf.manager.service.UserService;
import com.clf.manager.util.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @Autowired
    UserService userService;

    @RequestMapping("/username")
    public Result user(){
        Object o=SecurityUtils.getSubject().getPrincipal();
        if(o==null){
            return Result.fail("未登录，无用户");
        }
        else{
            return Result.succ(o);
        }
    }

    @RequestMapping("/errorpage")
    public Result error(){
        return Result.fail("权限不足");
    }

    @RequestMapping("/login")
    public Result login(@RequestParam("idPass") String username,
                        @RequestParam("pass") String password) {
        User user = userService.getById(username);
        if(user==null){
            return Result.fail("用户名不存在！");
        }
        if (StringUtils.isEmpty(user.getId()) || StringUtils.isEmpty(user.getPassword())) {
            return Result.fail("请输入用户名和密码！");
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
                user.getId(),
                user.getPassword()
        );
        try {
            subject.login(usernamePasswordToken);
        } catch (UnknownAccountException e) {
            return Result.fail("用户名不存在！");
        } catch (AuthenticationException e) {
            return Result.fail("账号或密码错误！");
        } catch (AuthorizationException e) {
            return Result.fail("没有权限");
        }
        return Result.succ(user);
    }

    @RequestMapping("/logout")
    public Result logout(){
        Subject subject= SecurityUtils.getSubject();
        subject.logout();
        return Result.succ(null);
    }
}
